<template>
  <el-dialog v-model="visible" width="450" destroy-on-close @close="handleClose" append-to-body draggable :loading="loading">
    <template #header>{{ TitleMap[dialogStatus] }}</template>
    <el-form ref="formRef" :model="modelForm" :rules="rules" label-width="80px" size="large" style="width: 95%">
      <input type="hidden" name="id" v-model="modelForm.id" />
      <el-form-item label="站名" prop="title">
        <el-input v-model="modelForm.title" />
      </el-form-item>
      <el-form-item label="网址" prop="url">
        <el-input v-model="modelForm.url" />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input v-model="modelForm.contact" />
      </el-form-item>
      <el-form-item label="备注" prop="introduce">
        <el-input v-model="modelForm.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit()">确认</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import useLoading from '@/hooks/loading'
import { TitleMap } from '@/config'
import { cloneDeep } from 'lodash'

interface EditProps {
  modelForm: any
  editVisible: boolean
  createData: any
  updateData: any
  setEditVisible: any
  categories: any
  models: any
  title?: string
  dialogStatus: string
}
const props = withDefaults(defineProps<EditProps>(), {
  editVisible: false,
  modelForm: {
    colPid: 0,
    ord: 0,
    title: '',
    description: '',
  },
  title: '',
  dialogStatus: 'create',
  createData: () => {},
  updateData: () => {},
  setEditVisible: () => {},
  models: [],
})
const { modelForm }: any = toRefs(props)
const { loading, setLoading } = useLoading()
const formRef = ref<any>(null)
const visible = ref(false)
const isImg = ref(false)
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  link: [{ required: true, message: '请输入链接', trigger: 'blur' }],
}

watch(
  () => props.editVisible,
  (show) => {
    visible.value = show
  }
)

// 监测上传状态
watch(
  () => modelForm.value.smallimg,
  (v) => {
    isImg.value = !!v
  }
)

const handleClose = () => {
  props.setEditVisible()
  formRef.value!.resetFields()
}

// 处理form数据
const handleForm = (form: any) => {
  return form
}

const handleSubmit = () => {
  formRef.value
    .validate((valid: any) => {
      if (!valid) return

      const data = unref(handleForm(cloneDeep(modelForm)))
      props.dialogStatus === 'create' ? props.createData(data) : props.updateData(data)
      handleClose()
    })
    .catch((error: any) => {
      console.log('error', error)
    })
    .finally(() => {
      setLoading(false)
    })
}
</script>
<style lang="scss"></style>
